package com.xzw.aop;


import com.xzw.mapper.OperateLogMapper;
import com.xzw.pojo.OperateLog;
import com.xzw.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.xzw.anno.Log)")
    public Object LogOperate(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 执行目标方法
        Object result = joinPoint.proceed();
        // 计算耗时
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;
        // 构建操作日志实体
        OperateLog oLog = new OperateLog();
        oLog.setOperateEmpId(getCurrentUserId());  // 获取当前登录员工ID
        oLog.setOperateTime(LocalDateTime.now());
        oLog.setClassName(joinPoint.getTarget().getClass().getName());
        oLog.setMethodName(joinPoint.getSignature().getName());
        oLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        oLog.setReturnValue(result != null ? result.toString() : "void");
        oLog.setCostTime(costTime);
        // 保存日志
        log.info("操作日志记录：{}", oLog);
        operateLogMapper.insert(oLog);
        return result;
    }

    private Integer getCurrentUserId() {
        return CurrentHolder.getCurrentId();
    }
}
